package org.example.runner;

import lombok.extern.slf4j.Slf4j;
import org.example.common.ServiceConfigParam;
import org.example.discovery.IServiceDiscovery;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.net.InetAddress;

/**
 * @author sxt
 * @version 1.0
 * @description 服务注册到注册中心
 * @date 2023/8/4 20:37
 */
@Slf4j
public class DiscoveryApplicationRunner implements ApplicationRunner {

    @Resource
    private IServiceDiscovery iServiceDiscovery;

    /**
     * 服务名
     */
    @Value("${spring.application.name}")
    private String serviceName;

    /**
     * 端口
     */
    @Value("${server.port}")
    private String port;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // ip
        InetAddress localHost = InetAddress.getLocalHost();
        String ip = localHost.getHostAddress();

        Assert.notNull(iServiceDiscovery, "IServiceDiscovery 服务注册与发现对象不能为空");
        Assert.notNull(serviceName, "服务名不能为空");
        Assert.notNull(ip, "ip不能为空");
        Assert.notNull(port, "端口不能为空");

        boolean result = iServiceDiscovery.registryService(new ServiceConfigParam(serviceName, ip, port));
        Assert.isTrue(result, "服务注册失败, 请检查...");
        log.info("服务{}注册成功", serviceName);
    }
}
